package com.mission.schedule.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.R;
import com.mission.schedule.add603.bean.UserNewLy;
import com.mission.schedule.applcation.App;
import com.mission.schedule.appwidget.PreUtils;
import com.mission.schedule.bean.RepeatBean;
import com.mission.schedule.bean.SuccessOrFailBean;
import com.mission.schedule.bean.TagCommandBean;
import com.mission.schedule.bean.WBA_FindFunctionMy;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.clock.QueryAlarmData;
import com.mission.schedule.clock.RepeatDateUtil;
import com.mission.schedule.clock.WriteAlarmClock;
import com.mission.schedule.constants.Const;
import com.mission.schedule.constants.PostSendMainActivity;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.cutimage.Crop;
import com.mission.schedule.db.DBHelper;
import com.mission.schedule.entity.CLRepeatTable;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.my160920.widget.CircleImageView;
import com.mission.schedule.service.ClockService;
import com.mission.schedule.service.DownAPKService;
import com.mission.schedule.service.DownNongLiService;
import com.mission.schedule.service.DownQianDaoService;
import com.mission.schedule.service.DownRepeatService;
import com.mission.schedule.service.LocalSynService;
import com.mission.schedule.service.MinAndMaxService;
import com.mission.schedule.service.NoteService;
import com.mission.schedule.service.ServerUtil;
import com.mission.schedule.service.UpdataTagService;
import com.mission.schedule.utils.ActivityManager1;
import com.mission.schedule.utils.AfterPermissionGranted;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.EasyPermissions;
import com.mission.schedule.utils.GetDeviceId;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.NetUtil.NetWorkState;
import com.mission.schedule.utils.RxPhotoUtils;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;
import com.mission.schedule.utils.Utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.yalantis.ucrop.UCrop;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

public class MainActivity extends FragmentActivity implements
        OnClickListener, EasyPermissions.PermissionCallbacks {

    private LayoutInflater inflater = null;
    // 竖屏
    private RelativeLayout main_botton_rl_schedule;
    public TextView tv_schedule_count;
    public TextView tv_my_count;
    public TextView tv_repeat_count;

    private RelativeLayout main_botton_rl_repeat;
    private RelativeLayout main_botton_rl_found;
    private RelativeLayout main_botton_rl_my, main_botton_rl_me;
    private Fragment[] mFragments = new Fragment[5];
    private RelativeLayout[] layouts;
    private Map<String, String> mainMap;
    /**
     * 左面菜单属性
     */
    CircleImageView image_img;
    TextView tv_memberlogin, tixingname_tv, hidden_tv;// , notification_tv
    Button exit_btn, tixing_btn, jifenduihuan_btn, help_btn, set_btn,
            todayend_bt;
    ImageView member_relative, tv_my_new, tv_me_new;
    LinearLayout tixing_ll, todayend_ll, my_main_l, bottom_na;
    // RelativeLayout img_rl;
    RelativeLayout help_rl;
    String untaskend;
    Bitmap backgroundbitmap = null;

    private String paths;
    private String clipPath = "";// 裁剪过后的图片路径
    private int picW;
    // private ImageLoadingListener animateFirstListener = new
    // AnimateFirstDisplayListener();
    Context context;
    SharedPrefUtil sharedPrefUtil;
    private LinearLayout top_ll_left;
    int myIndex = 0;
    // 导航栏底部
    private TextView tv_schedule, tv_myrepeat, tv_found, tv_my, tv_me;

    static String date = "";
    Bitmap bit = null;
    String path;
    int displaypixels;

    String userId = "";
    String backgroundname;
    int mScreenWidth;
    int mScreenHeight;

    private HomeKeyEventReceiver keyEventReceiver;
    String myfriendscount;

    String updatesettime;// 设置的更新时间
    private WakeLock wakeLock = null;
    String isYouKe = "1";
    List<Map<String, String>> nongliList = new ArrayList<Map<String, String>>();
    String downtime = "2016-01-01";// 新标签下载时间
    int heigh = 0;
    Bitmap headbitmap = null;
    private String mOutputPath;
    private String mDemoPath;
    ActivityManager1 activityManager = null;
    private DisplayImageOptions options; // DisplayImageOptions是用于设置图片显示的类
    //    private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
    private ImageLoader imageLoader;
    private boolean isyouke = false;
    View bottom_line;
    LocalBroadcastManager localBroadcastManager;
    NoticeOnRefresh noticeOnRefresh;

    /**
     * 发出标记
     */
    String persondowntime = "2016-01-01";

    private int getStatusBarHeight() {
        int result = 0;
        int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resId > 0) {
            result = getResources().getDimensionPixelSize(resId);
        }
        return result;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= 21) {
            //设置透明状态栏,这样才能让 ContentView 向上
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

//            ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
//            View mChildView = mContentView.getChildAt(0);
//            if (mChildView != null) {
//                //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
//                ViewCompat.setFitsSystemWindows(mChildView, false);
//            }
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
//                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            decorView.setSystemUiVisibility(option);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
            View statusBarView = mContentView.getChildAt(0);
            //移除假的 View
            if (statusBarView != null && statusBarView.getLayoutParams() != null &&
                    statusBarView.getLayoutParams().height == getStatusBarHeight()) {
                mContentView.removeView(statusBarView);
            }
            //不预留空间
//            if (mContentView.getChildAt(0) != null) {
//                ViewCompat.setFitsSystemWindows(mContentView.getChildAt(0), false);
//            }
        }
        setContentView(R.layout.activity_mymain1);
        PreUtils.RefreshAppWidget(this);
        isyouke = getIntent().getBooleanExtra("isyouke", false);
        activityManager = ActivityManager1.getInstance();
        activityManager.addActivities(this);

        EventBus.getDefault().register(this);
        context = this;
        inflater = LayoutInflater.from(this);
        picW = Utils.dipTopx(this, 80);


        localBroadcastManager = LocalBroadcastManager.getInstance(context);
        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction("noticeOnRefresh1");
        noticeOnRefresh = new NoticeOnRefresh();
        localBroadcastManager.registerReceiver(noticeOnRefresh, intentFilter1);

        imageLoader = ImageLoader.getInstance();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        mScreenHeight = metric.heightPixels;
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        userId = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0");
        myfriendscount = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.COUNT, "0");
        isYouKe = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.QIANDAODATE, DateUtil.formatDate(new Date()));
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISADMIN, "0");
        String background = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERBACKGROUNDPATH, "");
        if ("".equals(StringUtils.getIsStringEqulesNull(background))) {
            path = URLConstants.默认背景图片;
        } else {
            path = URLConstants.默认背景图片 + "=" + background;
        }
        date = DateUtil.formatDateTimeSs(new Date());
        int year = Integer.parseInt(date.substring(0, 4)) - 1;
        String beforeDownTime = String.valueOf(year) + date.substring(4, 19).toString();
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OLDUPDATETIME, beforeDownTime);
        updatesettime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UPDATESETTIME, "2016-01-01 00:00:00");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SCHTYPE, "0");
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        displaypixels = dm.widthPixels * dm.heightPixels;

        initview();
        initdata();
//        StartMaxAndMin();
        if (!isApplicationBroughtToBackground(context)) {
            Log.e("TAG", "noBack");
            String firstlogin = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0");
            if (!"0".equals(firstlogin)) {
                isNetWork();
            }
        }
//        else {
//            Log.e("TAG", "isBack");
//            UpLoadData();
//        }
        registerHomeKeyReceiver();// 注册监听按下home键
        initDate();

        persondowntime = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.PERSONDOWNTIME, "2016-01-01");

        boolean ismonth = getIntent().getBooleanExtra("ismonth", false);
        if (ismonth) {
            checkBoxState(2);
        } else {
            setFragmentIndicator(0);
        }
        numsn = new newnums();
        IntentFilter ifd = new IntentFilter();
        ifd.addAction("numsn");
        registerReceiver(numsn, ifd);

        loginReceiver = new LoginReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("loginReceiver");
        registerReceiver(loginReceiver, intentFilter);

    }

    newnums numsn = null;
    LoginReceiver loginReceiver = null;

    private void IntenetData() {
        heigh = Utils.dipTopx(context, (Utils.pxTodip(context, mScreenHeight) / 11) * 10);
        if (heigh == 0) {
            return;
        } else {
            Intent intent = new Intent(context, DownQianDaoService.class);
            intent.putExtra("heigh", heigh);
            intent.putExtra("firstLogin", "0");
            intent.setAction("updateData");
            intent.setPackage(getPackageName());
            startService(intent);
        }
    }


    public static MainActivity instance;


    /**
     * 清单未读数量更新
     */
    public void updateNoteTitleNoReadNums() {
        int count = App.getDBcApplication().getNoteTitleNotReadAll(userId);
        if (count > 0) {
            tv_my_count.setVisibility(View.VISIBLE);
//            tv_my_count.setText(count + "");
        } else {
            tv_my_count.setVisibility(View.GONE);
        }
    }

    boolean ifShowMonth = false;

    public class NoticeOnRefresh extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra("isMonth", false)) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bottom_na.setBackgroundColor(getResources().getColor(R.color.background_dibudaohang));
                        bottom_line.setVisibility(View.VISIBLE);
                        tv_schedule.setTextColor(getResources().getColor(R.color.text_dibudaohang));
                        tv_myrepeat.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
//                tv_found.setTextColor(getResources().getColor(R.color.text_dibudaohang));
                        tv_my.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
                        tv_me.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
                        for (int i = 0; i < layouts.length; i++) {
                            ImageView imageView = (ImageView) ((RelativeLayout) layouts[i].getChildAt(0)).getChildAt(1);
                            if (i == 0) {
                                imageView.setImageResource(bottom_choose[0]);
                            } else {
                                imageView.setImageResource(bottom_none_choose[i]);
                            }
                        }
                    }
                },200);
                ifShowMonth = true;
            } else {
                bottom_na.setBackgroundColor(getResources().getColor(R.color.transparent));
                bottom_line.setVisibility(View.GONE);
                tv_schedule.setTextColor(getResources().getColor(R.color.white));
                tv_myrepeat.setTextColor(getResources().getColor(R.color.white));
//                tv_found.setTextColor(getResources().getColor(R.color.white));
                tv_my.setTextColor(getResources().getColor(R.color.white));
                tv_me.setTextColor(getResources().getColor(R.color.white));
                for (int i = 0; i < layouts.length; i++) {
                    ImageView imageView = (ImageView) ((RelativeLayout) layouts[i].getChildAt(0)).getChildAt(1);
                    imageView.setImageResource(bottom_white[i]);
                }

                ifShowMonth = false;
            }
        }
    }


    /**
     * 判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    private void initview() {
        my_main_l = findViewById(R.id.my_main_l);
        bottom_na = findViewById(R.id.bottom_na);
        bottom_line = findViewById(R.id.bottom_line);
        tv_schedule = findViewById(R.id.tv_schedule);
        tv_myrepeat = findViewById(R.id.tv_myrepeat);
        tv_found = findViewById(R.id.tv_found);
        tv_my = findViewById(R.id.tv_my);
        tv_my_new = findViewById(R.id.tv_my_new);
        tv_me = findViewById(R.id.tv_me);
        tv_me_new = findViewById(R.id.tv_me_new);
    }

    @SuppressLint("NewApi")
    private void initdata() {
        if ("5.0.0".equals(getVersion())) {
            app.deleteCLAdsTable();
        } else if ("5.1.0".equals(getVersion())) {
            app.deleteCLAdsTable();
        }
        init();
    }

    public static void guoqipostpone() {
        List<Map<String, String>> guoqiList;
        try {
            guoqiList = app.queryAllSchData(19, 0, 0);
            if (guoqiList != null && guoqiList.size() > 0) {
                for (Map<String, String> map : guoqiList) {
                    if ("1".equals(map.get(ScheduleTable.schIsPostpone))) {
                        if (DateUtil.parseDate(map.get(ScheduleTable.schDate))
                                .before(DateUtil.parseDate(DateUtil.formatDate(new Date())))) {
                            date = DateUtil.formatDate(new Date());
                            app.updateScheduleDateData(Integer.parseInt(map
                                    .get(ScheduleTable.schID)), date, map.get(ScheduleTable.schTime));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() {
        layouts = new RelativeLayout[5];
        main_botton_rl_schedule = findViewById(R.id.main_botton_rl_schedule);
        main_botton_rl_schedule.setOnClickListener(this);
        layouts[0] = main_botton_rl_schedule;

        tv_schedule_count = findViewById(R.id.tv_schedule_count);
        tv_my_count = findViewById(R.id.tv_my_count);
        tv_repeat_count = findViewById(R.id.tv_repeat_count);

        main_botton_rl_repeat = findViewById(R.id.main_botton_rl_repeat);
        main_botton_rl_repeat.setOnClickListener(this);
        layouts[1] = main_botton_rl_repeat;

        main_botton_rl_found = findViewById(R.id.main_botton_rl_found);
        main_botton_rl_found.setOnClickListener(this);
        layouts[2] = main_botton_rl_found;

        main_botton_rl_my = findViewById(R.id.main_botton_rl_my);
        main_botton_rl_my.setOnClickListener(this);
        layouts[3] = main_botton_rl_my;

        main_botton_rl_me = findViewById(R.id.main_botton_rl_me);
        main_botton_rl_me.setOnClickListener(this);
        layouts[4] = main_botton_rl_me;
    }

    public void RepeatNotReadCount() {
        app.updateAllRepeatIsRead();
        int comerepeatcount = App.getDBcApplication().QueryAllChongFuData(0).size();
        if (comerepeatcount == 0) {
            tv_repeat_count.setVisibility(View.GONE);
        } else {
            tv_repeat_count.setText("");
            tv_repeat_count.setVisibility(View.VISIBLE);
        }
    }

    public void loadCount() {

        int noEndCount = App.getDBcApplication().QueryNowGuoQiWeiJieShuCount();// Integer.parseInt(mainMap.get("noEndCount"));
//        int newNoteCount = App.getDBcApplication().QueryNewNoteRedCount();
        if (noEndCount == 0) {
            tv_schedule_count.setVisibility(View.GONE);
        } else {
            tv_schedule_count.setText(noEndCount + "");
            tv_schedule_count.setVisibility(View.VISIBLE);
        }
    }

    public void addtv_schedule_count(int num) {
        int loadnum = 0;
        if (!tv_schedule_count.getText().toString().isEmpty()) {
            loadnum = Integer.valueOf(tv_schedule_count.getText().toString());
        }

        tv_schedule_count.setText((loadnum + num) + "");
        tv_schedule_count.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        top_ll_left = null;
//        if (myIndex == 0) {
//            top_ll_left = MyScheduleFragment.top_ll_left;
//            if (top_ll_left != null) {
//                top_ll_left.setOnClickListener(new OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        Intent intent = new Intent(context, AppSetActivity.class);
//                        context.startActivity(intent);
//                    }
//                });
//            }
//        } else if (myIndex == 1) {
//            top_ll_left = MyRepeatFragment.top_ll_left;
//            if (top_ll_left != null) {
//                top_ll_left.setOnClickListener(new OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        Intent intent = new Intent(context, AppSetActivity.class);
//                        context.startActivity(intent);
//                    }
//                });
//            }
//        } else if (myIndex == 2) {
//            top_ll_left = NewMyFoundFragment.top_ll_left;
//            if (top_ll_left != null) {
//                top_ll_left.setOnClickListener(new OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        Intent intent = new Intent(context, AppSetActivity.class);
//                        context.startActivity(intent);
//                    }
//                });
//            }
//        } else {
//            top_ll_left = QDListFragment.top_ll_left;
//            if (top_ll_left != null) {
//                top_ll_left.setOnClickListener(new OnClickListener() {
//
//                    @Override
//                    public void onClick(View v) {
//                        Intent intent = new Intent(context, AppSetActivity.class);
//                        context.startActivity(intent);
//                    }
//                });
//            }
//        }
    }

    private void isNetWork() {
        new Thread(() -> {
            if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
//
////                    Intent downRepeat = new Intent(context, DownCalenderService.class);
////                    downRepeat.setAction("DownCalender");
////                    downRepeat.putExtra("isOnRefresh", false);
////                    downRepeat.setPackage(getPackageName());
////                    startService(downRepeat);
////
//                    Intent DownCa = new Intent(context, DownCalenderNoteService.class);
//                    DownCa.setAction("DownCalenderNoteService");
//                    DownCa.setPackage(getPackageName());
//                    startService(DownCa);
//
//                    Intent intentnewf = new Intent(context, NoteService.class);
//                    intentnewf.setAction("notedData");
//                    intentnewf.putExtra("loadType", 2);//2 下拉下载
//                    intentnewf.setPackage(context.getPackageName());
//                    context.startService(intentnewf);
//
//                    Intent downCalender = new Intent(context, DownRepeatService.class);
//                    downCalender.setAction("DownRepeat");
//                    downCalender.putExtra("downreppath", URLConstants.重复转发下载 + "?cUid=" + userId);
//                    downCalender.setPackage(context.getPackageName());
//                    context.startService(downCalender);
//
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWLOCAL, "1").equals("1")) {
                    String path = "http://www.keytimeapp.com/user_regisTimetableByAddress.do?uId="
                            + (userId.equals("0") ? "" : userId) + "&data=TimeSheet_A_"
                            + GetDeviceId.getDeviceId(context).replaceAll(":","0").replaceAll("%", "1");
                    StringRequest request = new StringRequest(Method.GET, path,
                            result -> {
                                Gson gson = new Gson();
                                PhoneCodeLoginNewActivity.LoginBean loginBean = gson.fromJson(result, PhoneCodeLoginNewActivity.LoginBean.class);
                                if (loginBean.status == 0) {
                                    List<PhoneCodeLoginNewActivity.LoginBean.ListBean> list = loginBean.list;
                                    if (list.size() > 0) {
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.NewMyFoundFenXiangFirst, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USEREMAIL, list.get(0).uEmail);
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TELEPHONE, list.get(0).uMobile);
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERID, list.get(0).uId + "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERNAME, list.get(0).uNickName);
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERSTATE, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERBACKGROUNDPATH, list.get(0).uBackgroundImage);
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONREMARK, list.get(0).uPersontag);
                                        if (!"".equals(list.get(0).uPortrait)) {
                                            String str = list.get(0).uPortrait;
                                            str = str.replace("\\", "");
                                            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, str);
                                        }
                                        sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.U_ACC_NO, list.get(0).uAccNo);
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, list.get(0).uIsActive + "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SHUNYANTYPE, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "-1");
                                        Intent tagintent = new Intent(context, UpdataTagService.class);
                                        tagintent.setAction("UpdataTagService");
                                        tagintent.putExtra("down", "downtag");
                                        tagintent.setPackage(getPackageName());
                                        startService(tagintent);
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWLOCAL, "0");
                                        sharedPrefUtil.putString(getApplicationContext(), ShareFile.USERFILE, ShareFile.LOGINTYPE, "0");
                                    }
                                }
                            }, error -> {
                        Toast.makeText(this, "网络异常,请检测网络", Toast.LENGTH_SHORT).show();
                    });
                    request.setTag("qiandao");
                    request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                    App.getHttpQueues().add(request);
//                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, "-1").length() > 7) {

//                        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, "-1").substring(0, 7).equals("游客12110")) {
//                            String path = URLConstants.新游客试用 + "?phoneType=" + Build.MODEL.replace(" ", "") + "&version=" + getVersion() + "&pushMac=" + JPushInterface.getRegistrationID(context);
//                            StringRequest request = new StringRequest(Method.GET, path,
//                                    result -> {
//                                        if (!TextUtils.isEmpty(result)) {
//                                            try {
//                                                Gson gson = new Gson();
//                                                NewLoginActivity.Beans beans = gson.fromJson(result, NewLoginActivity.Beans.class);
//                                                if (beans.status == 0) {
//                                                    List<NewLoginActivity.Beans.ListBean> list = beans.list;
//                                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERNAME, "游客12101" + list.get(0).id);
//                                                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERID, -list.get(0).id + "");
//                                                    App.getDBcApplication().updateNoteSate(-list.get(0).id + "");
//                                                    userId = -list.get(0).id + "";
//                                                }
//                                            } catch (JsonSyntaxException e) {
//                                                e.printStackTrace();
//                                            }
//                                        }
//
//                                    }, volleyError -> {
//                                    });
//                            request.setTag("resgin");
//                            request.setRetryPolicy(new DefaultRetryPolicy(3000, 1, 1.0f));
//                            App.getHttpQueues().add(request);
//                        }
//                    }
                }

            } else {
                return;
            }
        }).start();
    }

    public void setmainbg() {
        String localpath = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
        if (!"".equals(localpath)) {
            if ("0".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.aa));
            } else if ("1".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.a));
            } else if ("2".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.b));
            } else if ("3".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.c));
            } else if ("4".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.d));
            } else if ("5".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.e));
            } else if ("6".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.f));
            } else if ("7".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.g));
            } else if ("8".equals(localpath)) {
                my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.h));
            } else {
                my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(localpath)));
            }
        } else {
            my_main_l.setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.a));
        }
    }

    private void loadBG() {
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISMOSTIMAGE, "").isEmpty()) {
            setmainbg();
        } else {
            Date today = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(today);
            int weekday = c.get(Calendar.DAY_OF_WEEK);
            if (weekday == 2) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE1, "").isEmpty()) {
                    my_main_l.setBackground(getResources().getDrawable(R.mipmap.a));
                } else {
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE1, "0").length() == 1) {
                        my_main_l.setBackgroundDrawable(getD(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE1, "0")));
                    } else {
                        my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE1, ""))));
                    }
                }
            }
            if (weekday == 3) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE2, "").isEmpty()) {
                    my_main_l.setBackground(getResources().getDrawable(R.mipmap.b));
                } else {
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE2, "a").length() == 1) {
                        my_main_l.setBackgroundDrawable(getD(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE2, "a")));
                    } else {
                        my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE2, ""))));
                    }
                }
            }
            if (weekday == 4) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE3, "").isEmpty()) {
                    my_main_l.setBackground(getResources().getDrawable(R.mipmap.c));
                } else {
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE3, "b").length() == 1) {
                        my_main_l.setBackgroundDrawable(getD(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE3, "b")));
                    } else {
                        my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE3, ""))));
                    }
                }
            }
            if (weekday == 5) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE4, "").isEmpty()) {
                    my_main_l.setBackground(getResources().getDrawable(R.mipmap.d));
                } else {
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE4, "c").length() == 1) {
                        my_main_l.setBackgroundDrawable(getD(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE4, "c")));
                    } else {
                        my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE4, ""))));
                    }
                }
            }
            if (weekday == 6) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE5, "").isEmpty()) {
                    my_main_l.setBackground(getResources().getDrawable(R.mipmap.e));
                } else {
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE5, "d").length() == 1) {
                        my_main_l.setBackgroundDrawable(getD(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE5, "d")));
                    } else {
                        my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE5, ""))));
                    }
                }
            }
            if (weekday == 7) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE6, "").isEmpty()) {
                    my_main_l.setBackground(getResources().getDrawable(R.mipmap.f));
                } else {
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE6, "e").length() == 1) {
                        my_main_l.setBackgroundDrawable(getD(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE6, "e")));
                    } else {
                        my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE6, ""))));
                    }
                }
            }
            if (weekday == 1) {
                if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE7, "").isEmpty()) {
                    my_main_l.setBackground(getResources().getDrawable(R.mipmap.g));
                } else {
                    if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE7, "f").length() == 1) {
                        my_main_l.setBackgroundDrawable(getD(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE7, "f")));
                    } else {
                        my_main_l.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeFile(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE7, ""))));
                    }
                }
            }
        }
    }

    /**
     * 进入程序执行下载操作
     */
    @Override
    protected void onResume() {
        super.onResume();
//        App.getDBcApplication().deleteErrorRepeat();

        loadBG();

        DBHelper helper = new DBHelper(this);


        if (getVersion().equals("V6.1.8")) {
            App.getDBcApplication().add618ScheduleTableColumns();
        }

        if (!helper.tabIsExist("tb_user_frends_task")) {
            App.getDBcApplication().Create_frends_task();
        }
        if (!helper.tabIsExist("tb_function_my")) {
            App.getDBcApplication().Create_tb_function_my();
        }
        if (!helper.tabIsExist("tb_timepreinstall_list_class1")) {
            App.getDBcApplication().Createtb_tb_timepreinstall_list_class1();
        }

        App.getDBcApplication().insert_tb_function_my();

        App.getDBcApplication().Create_Sch_key();

        List<TagCommandBean> list = app.QueryTagData(11);
        if (list.size() == 0) {
            String[] emptyTag = {"生活", "工作", "理财", "其它", "分类A", "分类B"};
            app.insertTagIntenetData(101, "生日", 0, "0", 0, 0, "1", "");
            if (list.size() < 6) {
                int b = 1;
                for (TagCommandBean bean : list) {
                    int updatestate = app.getCalenderTypestate(bean.ctgId) == 0 ? 2 : 1;
                    app.updateTagData(bean.ctgId, bean.ctgText, bean.ctgOrder, bean.ctgColor, bean.ctgType, updatestate, b + "", "");
                    b++;
                }
                int tagSize = 6 - list.size();
                for (int i = 0; i < 6; i++) {
                    if (i >= (6 - tagSize)) {
                        app.insertTagIntenetData(-(i + 1), emptyTag[i], i + 1, "0", 1, 1, "" + (i + 2), "");
                    }
                }
            } else {
                int b = 1;
                for (TagCommandBean bean : list) {
                    if (b < 7) {
                        int updatestate = app.getCalenderTypestate(bean.ctgId) == 0 ? 2 : 1;
                        app.updateTagData(bean.ctgId, bean.ctgText, bean.ctgOrder, bean.ctgColor, bean.ctgType, updatestate, b + "", "");
                        b++;
                    }
                }
            }
        }

//        if (!DateUtil.formatDate(new Date()).equals(
//                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UPDATEAPP, DateUtil.formatDate(new Date())))) {
//            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPDATEAPP, DateUtil.formatDate(new Date()));
//            getAPPVersion();
//        }

        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.WEEKCOLOR1, "").equals("") ||
                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.MONTHCOLOR2, "").equals("") ||
                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.YEARCOLOR3, "").equals("")) {
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.WEEKCOLOR1, "4");
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.MONTHCOLOR2, "3");
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.YEARCOLOR3, "2");
        }


        String firstlogin = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0");
        if (sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            if (!"0".equals(firstlogin)) {
                if (DateUtil.formatDate(new Date()).equals(
                        sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME, DateUtil.formatDate(new Date())))) {
//                    getUser_findTbUserMac();
                } else {
                    if (!DateUtil.formatDate(new Date()).equals(
                            sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date())))) {
                        sharedPrefUtil.putString(this, ShareFile.USERFILE, ShareFile.CHANGJIANDIANZAN, "");
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date()));
//                        getUser_findTbUserMac();
                    }
                }
                if (sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "0").equals("0")) {
                    addKongCalender();
                    sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "1");
                }
            } else {
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOGINTIME, DateUtil.formatDate(new Date()));
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date()));
//                downLocalQiandaoLog();
                if (sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "0").equals("0")) {
                    addKongCalender();
                    sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "1");
                }
            }
        } else {
            if (isyouke) {
                isyouke = false;
                addKongCalender();
            } else {
                if (DateUtil.formatDate(new Date()).equals(
                        sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME, DateUtil.formatDate(new Date())))) {
                    updateLoginDate();
                } else {
                    if (!DateUtil.formatDate(new Date()).equals(
                            sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date())))) {
                        sharedPrefUtil.putString(this, ShareFile.USERFILE, ShareFile.CHANGJIANDIANZAN, "");
                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOGINTIME2, DateUtil.formatDate(new Date()));
                        updateLoginDate();
                    }
                }
            }
        }

        String openstylestate = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.OPENSTYLESTATE, "0");
        if ("0".equals(openstylestate) || "1".equals(openstylestate)) {
            if (!"0".equals(firstlogin)) {
                CheckCreateRepeatSchData();
            }
        }
        if ("1".equals(openstylestate)) {
            if (!"0".equals(firstlogin)) {
                guoqipostpone();
            }
        }
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OPENSTYLESTATE, "2");
//        String refresh = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.REFRESHFRIEND, "0");
//        if (!"0".equals(refresh)) {
//            EventBus.getDefault().post(new FristFragment("3"));
//            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.REFRESHFRIEND, "0");
//        }

//        getFriendLyNumS();
//        DownFrendCalenderLy();

        RepeatNotReadCount();
        loadCount();

        JPushInterface.onResume(context);
    }

    private Drawable getD(String keycode) {
        Drawable drawable = null;
        switch (keycode) {
            case "0":
                drawable = getResources().getDrawable(R.mipmap.tmbj);
                break;
            case "a":
                drawable = getResources().getDrawable(R.mipmap.a);
                break;
            case "b":
                drawable = getResources().getDrawable(R.mipmap.b);
                break;
            case "c":
                drawable = getResources().getDrawable(R.mipmap.c);
                break;
            case "d":
                drawable = getResources().getDrawable(R.mipmap.d);
                break;
            case "e":
                drawable = getResources().getDrawable(R.mipmap.e);
                break;
            case "f":
                drawable = getResources().getDrawable(R.mipmap.f);
                break;
            case "g":
                drawable = getResources().getDrawable(R.mipmap.g);
                break;
            case "h":
                drawable = getResources().getDrawable(R.mipmap.h);
                break;


        }

        return drawable;

    }

    public static Drawable resizeImage2(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;// 不加载bitmap到内存中
        BitmapFactory.decodeFile(path, options);
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inSampleSize = 1;

//        if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
//            int sampleSize = (outWidth / width + outHeight / (height - Utils.dipTopx(context, 53) - (height / 11) - Utils.dipTopx(context, 50))) / 2;
//            options.inSampleSize = sampleSize;
//        }

//        options.inJustDecodeBounds = false;
        return new BitmapDrawable(BitmapFactory.decodeFile(path, options));
    }

    private void downLocalQiandaoLog() {
//        HttpUtils httpUtils = new HttpUtils(10000);
//        RequestParams params = new RequestParams();
//        params.addBodyParameter("uid", userId);
//        httpUtils.send(HttpMethod.POST, URLConstants.签到当月日志下行, params,
//                new RequestCallBack<String>() {
//
//                    @Override
//                    public void onFailure(HttpException e, String msg) {
//                    }
//
//                    @Override
//                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        if (!TextUtils.isEmpty(responseInfo.result)) {
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.QIANDAOSTRING, responseInfo.result);
//                        }
//                    }
//                });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (keyEventReceiver == null) {
            registerHomeKeyReceiver();// 注册监听home键按下
        }
    }

    /**
     * 新用户进入app需要创建指导日程
     */
    private void addKongCalender() {
        String date = DateUtil.formatDate(new Date());
        String time = "09:00";
        String maxTitleId = DateUtil.nowTime2();
//        App.getDBcApplication().insertScheduleData(1,
//                "安卓手机铃声不响的解决办法",
//                date, time, 1, 0, 0, 1, 1, 0, 0,
//                date + " " + time, "", 2, "01111", "0", 0, "", "",
//                0, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "", "", 0, 0, 0);
//        App.getDBcApplication().insertScheduleData(2,
//                "点击\"️○\"可以快速结束日程",
//                date, time, 1, 0, 0, 1, 0, 0, 0,
//                date + " " + time, "", 2, "11111", "", 0, "", "",
//                0, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "", "", 0, 0, 0);
//        App.getDBcApplication().insertScheduleData(3,
//                "侧滑可删除日程",
//                date, time, 1, 0, 0, 1, 0, 0, 0,
//                date + " " + time, "", 2, "21111", "", 0, "", "",
//                0, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "", "", 0, 0, 0);
//        App.getDBcApplication().insertScheduleData(4,
//                "什么是自动顺延？系统将会把过期的日程自动顺延到今天",
//                date, time, 1, 0, 1, 1, 0, 0, 0,
//                date + " " + time, "", 2, "31111", "", 0, "", "",
//                0, 0, 0, "完成任务", "g_88", "", 0, 0, 0, "", "", 0, 0, 0);
//
//
//        String[] childs = {"因为各个品牌的手机系统不一样，可能会让部分手机的铃声不响。如果手机铃声不响请联系客服。", "请联系客服QQ：3098997562", "请联系客服QQ：3098997562",
//                "请联系客服QQ：3098997562", "重要的事情要讲三遍。", "#备注#工作日上午10点到下午6点在线。"};
//        for (int i = 0; i < childs.length; i++) {
//            CalenderNoteBean.PageBean.ItemsBean bean = new CalenderNoteBean.PageBean.ItemsBean();
//            bean.titleId = "01111";
//            bean.uid = Integer.valueOf(userId);
//            bean.id = App.getDBcApplication().getCalenderMinId() - 1;
//            bean.style = 0;
//            bean.changeTime = DateUtil.nowTime();
//            bean.createTime = DateUtil.nowTime();
//            bean.ltype = 0;
//            bean.orderId = i + 1;
//            bean.endstate = 0;
//            bean.remark = "";
//            bean.contents = childs[i];
//            bean.titles = "安卓手机铃声不响的解决办法";
//            bean.imgPath = path;
//            bean.imgUrl = "";
//            bean.cpath = "";
//            bean.curl = "";
//            bean.sdesc = "";
//            bean.nums = "";
//            bean.localIds = i + "1111";
//            bean.shareUrl = "";
//            bean.remark1 = "";
//            bean.remark2 = "";
//            bean.remark3 = "";
//            bean.remark4 = "";
//            bean.remark5 = "";
//            bean.remark6 = "";
//
//            App.getDBcApplication().saveCalederNoteDetailData(bean);
//        }
//
//        Intent intent = new Intent(Const.SHUAXINDATA);
//        intent.putExtra("data", "success");
//        intent.putExtra("index", 1);
//        intent.putExtra("what", 2);
//        context.sendBroadcast(intent);
        if (sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("0")) {
            List<WBA_FindFunctionMy.ListBean> listBeanList = new ArrayList<>();
            listBeanList.add(App.getDBcApplication().get_tb_function_my("100"));
            listBeanList.add(App.getDBcApplication().get_tb_function_my("101"));
            listBeanList.add(App.getDBcApplication().get_tb_function_my("104"));
            for (WBA_FindFunctionMy.ListBean listbean : listBeanList) {
                maxTitleId = DateUtil.nowTime2();
                RepeatBean bean = RepeatDateUtil.dateTimeToChildAlarmDate("23:59", 1, "", "", "0");
                App.getDBcApplication().insertCLRepeatTableData(0, 0,
                        0, 1, 1, 0, 0, 0, 1,
                        "[]", bean.repNextCreatedTime,
                        bean.repLastCreatedTime,
                        DateUtil.formatDateTime(new Date()),
                        bean.repNextCreatedTime, listbean.name,
                        DateUtil.formatDateTime(new Date()), maxTitleId, "0",
                        "23:59", "完成任务", "g_88",
                        DateUtil.formatDateTime(new Date()), 0, "", 0,
                        "", "", 0, 0, 0, "", "",
                        0, 0, "", 0, 0, "0", "", "", "", "", "", "");
                App.getDBcApplication().insertScheduleData(listbean.name,
                        bean.repNextCreatedTime.substring(0, 10),
                        bean.repNextCreatedTime.substring(11, 16),
                        1, 0, 0, 0, 0, 0,
                        0, bean.repNextCreatedTime, "", 0, maxTitleId, "0",
                        App.getDBcApplication().repschId, bean.repNextCreatedTime,
                        DateUtil.formatDateTime(new Date()), 0, 0,
                        1, "完成任务", "g_88", "", 0, 0,
                        0, "", "", 0, 0, 0, 0, "", "0", "0");
                App.getDBcApplication().updateRepeatremark2(App.getDBcApplication().repschId + "", "" + listbean.id);
                App.getDBcApplication().updateRepeatTimeNextDate(App.getDBcApplication().repschId + "", bean.repNextCreatedTime);
                Intent intent = new Intent(Const.SHUAXINDATA);
                intent.putExtra("data", "success");
                intent.putExtra("index", 1);
                intent.putExtra("what", 2);
                sendBroadcast(intent);
            }
        }
        bwl();


    }

    String[] images = {"20170420/79502.png"};//, "20170520/102567.png", "20170520/973198.png"
    String[] titles = {"为什么要用“时间表App”?"};//, "清单使用攻略", "旅游或出差前的准备事项"
    String[][] contents = {
            {"#与遗忘作斗争#", "现代生活节奏让每个人很难不忘掉一些与时间有关的重要信息，如某理财产品的到期时间、年检时间、优惠券或抵用券的期限、续保续费或还贷时间、收房租时间，还有一些重要的日子等等。",
                    "时间表App就是帮你记住这些信息，并在时间快到的时候提醒你。", "#与不坚持作斗争#", "很多方面要达到想要的效果，需要日积月累持之以恒，如锻炼身体、个人护理、学习外语背单词、读书写日记等等。但人的惰性常常促使你找一些理由，让你三天打鱼，两天晒网，最后可能是放弃。",
                    "时间表App就是在关键时候提醒你，要坚持下去，帮助你具备一定的恒心。", "#与拖延症作斗争#", "“拖延症”是现代社会最普遍的通病，几乎人人都有。这是因为大多数都喜欢挑简单而又愉快的事做，而把麻烦一点或者不大愿意做的事推到明天或以后，拖延的理由也各种各样，拖延久了也容易麻木。",
                    "时间表App就是在你的眼前浮现这些要做的事情，提醒你正在“拖延”，给你一点“压力”，但又允许你进行轻松的“推后”操作，让它们暂离你的视线，保持今天的“好心情”。"}};

    /**
     * ,
     * {"#什么是归档#用户有暂时不用的清单，可设为归档清单。归档清单只在归档列表中显示。", "#粘贴功能#用户可将已复制的文字，点击赞贴快速生成清单。自动生成样式。",
     * "#排序#点击排序可以快速调整清单内容的顺序。", "#样式#清单列表有四种样式：1）核对样式，有勾选框；2）圆点样式；3）序列样式，系统自动生成序号；4）无样式。",
     * "#设为标题#清单的每行内容都可设为标题。", "#插入图片#清单详情的菜单选项中有“插入图片”功能。", "#生成长图#可快速将清单生成为一张图片，便于转发和分享。",
     * "#全文复制#复制清单的全部内容。"},
     * {"护照+身份证", "手机", "充电器", "耳机", "银行卡（信用卡）", "现金若干", "头靠枕", "换洗衣服", "厚外套（一些城市早晚温差较大）",
     * "手套+围巾", "墨镜", "雨伞/太阳伞", "防晒霜SPF", "防晒帽、防晒袖", "感冒药/安定片", "创可贴", "旅行装洗漱用品", "护肤化妆品",
     * "剃须刀", "睡衣裤", "回家的钥匙", "网上所有预定信息图片", "其它"}
     */

    private void bwl() {

        for (int i = 0; i < titles.length; i++) {
            int id = App.getDBcApplication().getTiMinId() - 1;
            String titleid = i + "111";
            NoteTitleDetailBean.TDelListBean bean = new NoteTitleDetailBean.TDelListBean();
            bean.titleId = titleid;
            bean.uid = Integer.valueOf(userId);
            bean.id = id;
            if (i == 2) {
                bean.styles = 2;
            } else {
                bean.styles = 1;
            }

            bean.changeTime = DateUtil.nowTime();
            bean.createTime = DateUtil.nowTime();
            bean.localTimes = DateUtil.nowTime();
            bean.ltype = 0;
            bean.orderId = 0;
            bean.copys = "0";
            bean.filed = "0";
            bean.titles = titles[i];
            bean.imgPath = images[i];
            bean.imgUrl = "";
            bean.nums = "";
            bean.shareUrl = "";
            bean.remark = "0";
            bean.remark1 = "0";
            bean.remark2 = "";
            bean.remark3 = "";
            bean.pname = "";
            bean.puid = 0;
            bean.states = 0;
            bean.sends = 0;
            bean.openState = 0;
            bean.other1 = "0";

            App.getDBcApplication().saveNoteTitleData(bean);
            App.getDBcApplication().updateNoteTitleState(bean.titleId, userId, 0, false);
            for (int j = 0; j < contents[i].length; j++) {
                NoteTitleDetailBean.ListBean listBean = new NoteTitleDetailBean.ListBean();
                listBean.titleId = titleid;
                listBean.uid = Integer.valueOf(userId);
                listBean.id = App.getDBcApplication().getMinId() - 1;
                if (i == 2) {
                    listBean.style = 2;
                } else {
                    listBean.style = 1;
                }
                listBean.changetime = DateUtil.nowTime();
                listBean.createTime = DateUtil.nowTime();
                listBean.lType = 0;
                listBean.orderId = j + 1;
                listBean.endstate = 0;
                listBean.remark = "";
                listBean.contents = contents[i][j];
                listBean.titles = titles[i];
                listBean.imgPath = images[i];
                listBean.imgUrl = "";
                listBean.cpath = "";
                listBean.curl = "";
                listBean.nums = "";
                listBean.shareUrl = "";
                listBean.remark1 = "";
                listBean.remark2 = "";
                listBean.remark3 = "";
                listBean.remark4 = "";

                App.getDBcApplication().saveNoteDetailData(listBean);
                App.getDBcApplication().updateNoteTitleDetailState("0", listBean.id, userId, 0, false);
            }
        }

    }


    /**
     * 退出程序执行同步操作
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (keyEventReceiver != null) {
            unregisterReceiver(keyEventReceiver);
            keyEventReceiver = null;
        }
        JPushInterface.onPause(context);
    }

    private void UpLoadData() {
        if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
            if (sharedPrefUtil.getString(getApplication(), ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                Intent intentnote = new Intent(getApplication(), NoteService.class);
                intentnote.setAction("notedData");
                intentnote.putExtra("loadType", 1);
                intentnote.setPackage(getPackageName());
                startService(intentnote);

                Intent LocalSyni = new Intent(context, LocalSynService.class);
                LocalSyni.setAction("LocalSynService");
                LocalSyni.putExtra("isMinLocal", true);
                LocalSyni.setPackage(context.getPackageName());
                context.startService(LocalSyni);

                IntenetData();

                Intent intent = new Intent(context, DownNongLiService.class);
                intent.setAction("com.mission.schedule.service.DownNongLiService");
                intent.setPackage(getPackageName());
                startService(intent);
            }
        }
    }

    /**
     * 页面适配器
     */
    // public class FragmentAdapter extends FragmentPagerAdapter {
    //
    // public FragmentAdapter(FragmentManager fm) {
    // super(fm);
    // }
    //
    // @Override
    // public Fragment getItem(int arg0) {
    // return fragments.get(arg0);
    // }
    //
    // @Override
    // public int getCount() {
    // return fragments.size();
    // }
    //
    // }
    boolean autoFag = false;
    private static final int RC_LOCATION_CONTACTS_PERM = 124;

    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    private void checkPhonePermission() {
        if (Build.VERSION.SDK_INT < 23) {
            autoFag = true;
        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
            if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
                // Have permissions, do the thing!
                autoFag = true;
            } else {
                // Ask for both permissions
                EasyPermissions.requestPermissions(this, "该功能需要此权限，为了保证应用正常运行!",
                        RC_LOCATION_CONTACTS_PERM, perms);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
            autoFag = true;
        } else {
            autoFag = false;
        }
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.d("TAG", "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
// (Optional) Check whether the user denied permissions and checked NEVER ASK AGAIN.
        // This will display a dialog directing them to enable the permission in app settings.
        EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
                getString(R.string.rationale_ask_again),
                R.string.action_settings, R.string.cancel, null, perms);
    }

    @Override
    public void onClick(View v) {
        SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context,
                ShareFile.USERFILE);
        switch (v.getId()) {
            case R.id.member_relative:
                // 更换左边菜单的背景图
                dialogShow();
                break;
            case R.id.image_img:
                isYouKe = sharedPrefUtil.getString(context, ShareFile.USERFILE,
                        ShareFile.ISYOUKE, "1");
                // 点击头像进入到个人详细信息
                if ("1".equals(isYouKe)) {
                    startActivity(new Intent(context, PersonMessageActivity.class));
                } else {
                    Intent newt = new Intent(context, PhoneCodeLoginActivity.class);
                    newt.putExtra("type", 1);
                    newt.putExtra("login", true);
                    startActivity(newt);
                }
                break;
            case R.id.jifenduihuan_btn:// 积分兑换
                startActivity(new Intent(context, JiFenDuiHuanActivity.class));
                break;
            case R.id.exit_btn:
//                try {
//                    isYouKe = sharedPrefUtil.getString(context, ShareFile.USERFILE,
//                            ShareFile.ISYOUKE, "1");
//
//                    if ("1".equals(isYouKe)) {
//                        List<Map<String, String>> unSchUpdateList = app.queryAllSchData(-1, 0, 0);
//                        List<Map<String, String>> unRepUpdateList = app.QueryAllChongFuData(2);
//                        List<NoteTitleDetailBean.TDelListBean> tDelListBeanArrayList = app.getAllNoteTitlesData(userId, true);
//                        List<NoteTitleDetailBean.ListBean> listBeanList = app.getAllNoteDetailData(userId, true);
//                        List<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> itemsBeanList = app.getAllNewFriendData(userId, true);
//                        if ((unSchUpdateList != null && unSchUpdateList.size() > 0) || (unRepUpdateList != null && unRepUpdateList.size() > 0)
//                                || (tDelListBeanArrayList != null && tDelListBeanArrayList.size() > 0) || (listBeanList != null && listBeanList.size() > 0)
//                                || (itemsBeanList != null && itemsBeanList.size() > 0)) {
//                            startActivity(new Intent(context, ExitAlterActivity.class));
//                        } else {
//                            WriteAlarmClock.clearAlarmClock(getApplicationContext());
//                            if (!"".equals(sharedPrefUtil.getString(context,
//                                    ShareFile.USERFILE, ShareFile.TELEPHONE, ""))) {
//                                sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                        ShareFile.TELEPHONE, "");
//                            } else {
//                                sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                        ShareFile.USEREMAIL, "");
//                            }
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.ISADMIN, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.USERID, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.USERNAME, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.USERBACKGROUNDPATH, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.USERPHOTOPATH, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.USERSTATE, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.FIRSTLOGIN, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.U_ACC_NO, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.MAXFOCUSID, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.OUTWEEKFAG, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.UPDATESETTIME, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.UPDATENOTESETTIME, "2016-01-01");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.DOWNSCHTIME, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.DOWNREPTIME, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.RINGSTATE, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.ISYOUKE, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.DOWNTAGDATE, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.OPENSTYLESTATE, "2");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.FRIENDDOWNSCHTIME, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.FRIENDDOWNRepTIME, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.FRIENDDOWNOldTIME, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.PUSH_ALIAS, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.REFRESHFRIEND, "0");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.FIRSTDOWNFOCUSSCH, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.SHOUCANGDATA, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.DOWNNEWFOCUSSHARESCHDATE, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.DOWNNEWFOCUSSHAREREPDATE, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.KuaiJieSouSuo, "");
//                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
//                                    ShareFile.SHAREDATA, "");
//                            ClearMAC("");
//                            // RuntimeCmdManager.clearAppUserData(getPackageName());
//                            /**
//                             *
//                             */
//                            app.douleClear();
//                            sharedPrefUtil
//                                    .putString(
//                                            context,
//                                            ShareFile.USERFILE,
//                                            ShareFile.PERSONDOWNTIME,
//                                            "2016-01-01");
//                            startActivity(new Intent(context, NewLoginActivity.class));
//                            Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
//                            Bundle extras = new Bundle();
//                            intentappwidget.putExtras(extras);
//                            sendBroadcast(intentappwidget);
//                            activityManager.doAllActivityFinish();
//                        }
//
//                    } else {
//                        startActivity(new Intent(context, LogoutActivity.class));
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                break;
            case R.id.tixing_ll: // 提醒模式
                alterRingDialog();
                break;
            case R.id.help_btn:
                startActivity(new Intent(context, HelpActivity.class));
                break;
            // case R.id.notification_tv:
            // startActivity(new Intent(context, HelpActivity.class));
            // break;
            case R.id.help_rl:
                startActivity(new Intent(context, HelpActivity.class));
                break;
            case R.id.tixing_btn: // 提醒模式
                alterRingDialog();
                break;
            case R.id.set_btn:
                startActivity(new Intent(context, SettingActivity.class));
                break;
            case R.id.todayend_ll:
                untaskend = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                if ("0".equals(untaskend)) {
                    hidden_tv.setText("隐藏");
                    hidden_tv.setTextColor(context.getResources().getColor(R.color.sunday_txt));
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "1");
                } else {
                    hidden_tv.setText("显示");
                    hidden_tv.setTextColor(context.getResources().getColor(R.color.mingtian_color));
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                }
                break;
            case R.id.hidden_tv:
                untaskend = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                if ("0".equals(untaskend)) {
                    hidden_tv.setText("隐藏");
                    hidden_tv.setTextColor(context.getResources().getColor(R.color.sunday_txt));
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "1");
                } else {
                    hidden_tv.setText("显示");
                    hidden_tv.setTextColor(context.getResources().getColor(R.color.mingtian_color));
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                }
                Intent intent_app1 = new Intent();
                intent_app1.setAction("appwidget");
                intent_app1.putExtra("aappwidget1", true);
                context.sendBroadcast(intent_app1);
                break;
            case R.id.todayend_bt:
                untaskend = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                if ("0".equals(untaskend)) {
                    hidden_tv.setText("显示");
                    hidden_tv.setTextColor(context.getResources().getColor(R.color.mingtian_color));
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "1");
                } else {
                    hidden_tv.setText("隐藏");
                    hidden_tv.setTextColor(context.getResources().getColor(R.color.sunday_txt));
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "0");
                }
                Intent intent_app2 = new Intent();
                intent_app2.setAction("appwidget");
                intent_app2.putExtra("aappwidget1", true);
                context.sendBroadcast(intent_app2);
                break;
            case R.id.main_botton_rl_schedule:
//                getFriendLyNumS();
                if (ifShowMonth) {
                    bottom_na.setBackgroundColor(getResources().getColor(R.color.background_dibudaohang));
                    bottom_line.setVisibility(View.VISIBLE);
                    tv_schedule.setTextColor(getResources().getColor(R.color.text_dibudaohang));
                    tv_myrepeat.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
//                    tv_found.setTextColor(getResources().getColor(R.color.text_dibudaohang));
                    tv_my.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
                    tv_me.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
                    for (int i = 0; i < layouts.length; i++) {
                        ImageView imageView = (ImageView) ((RelativeLayout) layouts[i].getChildAt(0)).getChildAt(1);
                        if (i == 0) {
                            imageView.setImageResource(bottom_choose[0]);
                        } else {
                            imageView.setImageResource(bottom_none_choose[i]);
                        }
                    }
                } else {
                    checkBoxState(0);
                    myIndex = 0;
                    onStart();
                }
                break;

            case R.id.main_botton_rl_repeat:
//                getFriendLyNumS();
                checkBoxState(1);
                myIndex = 1;
                onStart();
                break;

            case R.id.main_botton_rl_found:
                checkBoxState(2);
//                getFriendLyNumS();
                myIndex = 2;
                onStart();
                break;

            case R.id.main_botton_rl_my:
                checkBoxState(3);
//                getFriendLyNumS();
//                tv_my_new.setVisibility(View.GONE);
                myIndex = 2;
                onStart();
                break;
            case R.id.main_botton_rl_me:
                checkBoxState(4);
//                getFriendLyNumS();
//                tv_my_new.setVisibility(View.GONE);
                myIndex = 3;
                onStart();
                break;
            default:
                break;
        }
    }

    int[] bottom_none_choose = new int[]{R.mipmap.btn_home_h,R.mipmap.btn_calendar_h,
            R.mipmap.btn_repet_h, R.mipmap.btn_list_h, R.mipmap.btn_my_h};
    int[] bottom_choose = new int[]{R.mipmap.btn_home_g,R.mipmap.btn_calendar_l,
            R.mipmap.btn_repet_l,  R.mipmap.btn_list_l, R.mipmap.btn_my_l};
    int[] bottom_white = new int[]{R.mipmap.btn_home_b,R.mipmap.btn_calendar_b,
            R.mipmap.btn_repet_b,  R.mipmap.btn_list_b, R.mipmap.btn_my_b};

    private void checkBoxState(int index) {
        setFragmentIndicator(index);
        if (index == 0) {
            for (int i = 0; i < layouts.length; i++) {
                ImageView imageView = (ImageView) ((RelativeLayout) layouts[i].getChildAt(0)).getChildAt(1);
                imageView.setImageResource(bottom_white[i]);
            }
        } else {
            for (int i = 0; i < layouts.length; i++) {
                ImageView imageView = (ImageView) ((RelativeLayout) layouts[i].getChildAt(0)).getChildAt(1);
                if (i == index) {
                    imageView.setImageResource(bottom_choose[i]);
                } else {
                    imageView.setImageResource(bottom_none_choose[i]);
                }
            }
        }

//        if (index > 0) {
//            ifShowMonth = false;
//            Intent intent = new Intent("noticeOnRefresh2");
//            localBroadcastManager.sendBroadcast(intent);
//        }
    }

    private void setFragmentIndicator(int whichIsDefault) {
        if (whichIsDefault == 0) {
            bottom_na.setBackgroundColor(getResources().getColor(R.color.transparent));
            bottom_line.setVisibility(View.GONE);
        } else {
            bottom_na.setBackgroundColor(getResources().getColor(R.color.background_dibudaohang));
            bottom_line.setVisibility(View.VISIBLE);
        }
        if (whichIsDefault == 0) {
            tv_schedule.setTextColor(getResources().getColor(R.color.white));
            tv_myrepeat.setTextColor(getResources().getColor(R.color.white));
            tv_found.setTextColor(getResources().getColor(R.color.white));
            tv_my.setTextColor(getResources().getColor(R.color.white));
            tv_me.setTextColor(getResources().getColor(R.color.white));
//            EventBus.getDefault().post(new FristFragment("0"));
        } else if (whichIsDefault == 1) {
            tv_schedule.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_myrepeat.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang));
            tv_found.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_my.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_me.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
//            EventBus.getDefault().post(new FristFragment("1"));
        } else if (whichIsDefault == 2) {
            tv_schedule.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_myrepeat.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_found.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang));
            tv_my.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_me.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
//            EventBus.getDefault().post(new FristFragment("2"));
        } else if (whichIsDefault == 3) {
            tv_schedule.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_myrepeat.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_found.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_my.setTextColor(getResources()
                    .getColor(R.color.text_dibudaohang));
            tv_me.setTextColor(getResources().getColor(R.color.text_dibudaohang_moren));
//            EventBus.getDefault().post(new FristFragment("3"));
        } else {
            tv_schedule.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_myrepeat.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_found.setTextColor(getResources().getColor(
                    R.color.text_dibudaohang_moren));
            tv_my.setTextColor(getResources()
                    .getColor(R.color.text_dibudaohang_moren));
            tv_me.setTextColor(getResources().getColor(R.color.text_dibudaohang));
//            EventBus.getDefault().post(new FristFragment("3"));
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        mFragments[0] = fragmentManager.findFragmentById(R.id.fragment_MySchedule);
        mFragments[1] = fragmentManager.findFragmentById(R.id.fragment_MyRepeat);
        mFragments[2] = fragmentManager.findFragmentById(R.id.fragment_MyFound);
        mFragments[3] = fragmentManager.findFragmentById(R.id.fragment_my);
        mFragments[4] = fragmentManager.findFragmentById(R.id.fragment_me);
        fragmentManager.beginTransaction().hide(mFragments[0])
                .hide(mFragments[1]).hide(mFragments[2]).hide(mFragments[3]).hide(mFragments[4])
                .show(mFragments[whichIsDefault]).commitAllowingStateLoss();
    }


    public boolean setPrivateXml(String fileName, String key, String val) {
        try {
            SharedPreferences sp = getSharedPreferences(fileName, MODE_PRIVATE);
            SharedPreferences.Editor e = sp.edit();
            e.putString(key, val);
            e.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 101:
//                    tv_my_new.setVisibility(View.VISIBLE);
                    break;
                case 102:
//                    tv_my_new.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }

    };
    private boolean isClose;

    @Override
    public void onBackPressed() {
        if (!isClose) {
            isClose = true;
            Toast.makeText(this, "再按一次返回键关闭程序", Toast.LENGTH_SHORT).show();
            handler.postDelayed(runnable, 5000);
        } else {
            Log.e("TAG", "isBack");
            UpLoadData();
            handler.removeCallbacks(runnable);
            final Window win = getWindow();
            win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
            sharedPrefUtil.putString(context, ShareFile.USERFILE,
                    ShareFile.OUTWEEKFAG, "0");
            sharedPrefUtil.putString(context, ShareFile.USERFILE,
                    ShareFile.OPENSTYLESTATE, "1");
            sharedPrefUtil.putString(context, ShareFile.USERFILE,
                    ShareFile.REFRESHFRIEND, "0");
            initDate();
            WriteAlarmClock.writeAlarm(getApplicationContext());

            if (NewLoginActivity.instance != null) {
                if (!NewLoginActivity.instance.isDestroyed() || !NewLoginActivity.instance.isFinishing()) {
                    NewLoginActivity.instance.finish();
                }
            }
//            Intent intentioned = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
//            Bundle extras = new Bundle();
//            intentioned.putExtras(extras);
//            sendBroadcast(intentioned);
            PreUtils.RefreshAppWidget(context);
            activityManager.doAllActivityFinish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {// 竖屏
            if (!isClose) {
                isClose = true;
                Toast.makeText(this, "再按一次返回键关闭程序", Toast.LENGTH_SHORT).show();
                handler.postDelayed(runnable, 5000);
                return true;
            } else {
                Log.e("TAG", "isBack");
                UpLoadData();
                handler.removeCallbacks(runnable);
                final Window win = getWindow();
                win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "0");
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OPENSTYLESTATE, "1");
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.REFRESHFRIEND, "0");
                initDate();
                WriteAlarmClock.writeAlarm(getApplicationContext());
                if (NewLoginActivity.instance != null) {
                    if (!NewLoginActivity.instance.isDestroyed() || !NewLoginActivity.instance.isFinishing()) {
                        NewLoginActivity.instance.finish();
                    }
                }
                activityManager.doAllActivityFinish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            isClose = false;
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "0");
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // if (mUploadPicHttpTask != null && !mUploadPicHttpTask.isCancelled())
        // {
        // mUploadPicHttpTask.cancel(true);
        // }
        if (headbitmap != null) {
            headbitmap.recycle();
        }
        if (bit != null) {
            bit.recycle();
        }
        bit = null;
        if (backgroundbitmap != null) {
            backgroundbitmap.recycle();
        }
        backgroundbitmap = null;
//        MyScheduleFragment.top_ll_left = null;
//        MyRepeatFragment.top_ll_left = null;
//        NewMyFoundFragment.top_ll_left = null;
//        NewFriendsFragment.top_ll_left = null;
        top_ll_left = null;
        App.getHttpQueues().cancelAll("down");
        App.getHttpQueues().cancelAll("downtag");
        App.getHttpQueues().cancelAll("addset");
        EventBus.getDefault().unregister(this);
        if (numsn != null) {
            unregisterReceiver(numsn);
        }
        if (loginReceiver != null) {
            unregisterReceiver(loginReceiver);
        }
//        handler.removeCallbacksAndMessages(null);
        // android.os.Process.killProcess(android.os.Process.myPid());
        // releaseWakeLock();
    }

    private void dialogShow() {
        Dialog dialog = new Dialog(this, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(this);
        View more_pop_menu = fac.inflate(R.layout.dialog_selecttypecamera, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth() - 30;
        dialog.show();

        new MyClickClass(more_pop_menu, dialog);
    }

    class MyClickClass implements OnClickListener {

        private Dialog dialog;
        private Button dialog_button_photo;
        // private Button dialog_button_moren;
        private Button dialog_button_cancel;

        public MyClickClass(View view, Dialog dialog) {
            this.dialog = dialog;
            dialog_button_photo = (Button) view
                    .findViewById(R.id.dialog_button_photo);
            dialog_button_photo.setOnClickListener(this);
            // dialog_button_moren = (Button) view
            // .findViewById(R.id.dialog_button_moren);
            // dialog_button_moren.setOnClickListener(this);
            dialog_button_cancel = (Button) view.findViewById(R.id.dialog_button_cancel);
            dialog_button_cancel.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            // Intent intent = null;
            switch (v.getId()) {
                case R.id.dialog_button_photo:
                    // ImageCutUtils.openLocalImage(MainActivity.this);
//				ImageCutTools.getInstance().selectPicture();
                    checkPhonePermission();
                    if (autoFag) {
                        Crop.pickImage(MainActivity.this);
                    } else {
                        Toast.makeText(context, "权限已禁止访问!", Toast.LENGTH_LONG).show();
                    }

                    break;
                case R.id.dialog_button_cancel:
                    break;
            }
            dialog.dismiss();
        }
    }

    /* 根据uri返回文件路径 */
    public String getPath(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        // 好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = managedQuery(uri, proj, null, null, null);
        // 按我个人理解 这个是获得用户选择的图片的索引值
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        // 将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        // 最后根据索引值获取图片路径
        return cursor.getString(column_index);
    }

    public final static Bitmap lessenUriImage(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回 bm 为空
        options.inJustDecodeBounds = false; // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = (int) (options.outHeight / (float) 320);
        if (be <= 0) be = 1;
        options.inSampleSize = be; // 重新读入图片，注意此时已经把 options.inJustDecodeBounds
        // 设回 false 了
        bitmap = BitmapFactory.decodeFile(path, options);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        System.out.println(w + " " + h); // after zoom
        return bitmap;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == Activity.RESULT_OK) {
//            if (data != null && (requestCode == Const.REQUEST_CLIP_IMAGE || requestCode == Const.REQUEST_TAKE_PHOTO)) {
//                String path = PhotoActionHelper.getOutputPath(data);
//                Intent intent = new Intent("headImageBackReceiver");
//                intent.putExtra("path", path);
//                sendBroadcast(intent);
//            }
//        }

        if (data != null) {
            String fileName = "HeaderImage_" + String.valueOf(System.currentTimeMillis()) + ".png";

            Uri selectImageUri = data.getData();

            if (selectImageUri != null) {
                Uri mDestinationUri = Uri.fromFile(new File(getCacheDir(), fileName));
                UCrop.of(selectImageUri, mDestinationUri).withMaxResultSize(480, 480).withAspectRatio(1, 1).start(MainActivity.this);
            }
            if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
                final Uri resultUri = UCrop.getOutput(data);
                String path = RxPhotoUtils.getRealFilePath(MainActivity.this, resultUri);
                if (path != null) {
                    Intent intent = new Intent("headImageBackReceiver");
                    intent.putExtra("path", path);
                    sendBroadcast(intent);
                }
            } else if (resultCode == UCrop.RESULT_ERROR) {
                Toast.makeText(context, "图片裁剪失败!", Toast.LENGTH_SHORT).show();
            }
        }
    }


    // ============================每次打开程序生成子记事============================================//
    static List<Map<String, String>> repeatlist = new ArrayList<Map<String, String>>();
    static Map<String, String> map;
    static App app = App.getDBcApplication();

    public void CheckCreateRepeatSchData() {

        repeatlist = app.QueryAllChongFuData(3);
        Log.e("TAG", "CheckCreateRepeatSchData-start" + repeatlist.size());
        boolean isNewChild = false;
        for (int i = 0; i < repeatlist.size(); i++) {
            map = repeatlist.get(i);

            Date nextDate = DateUtil.parseDateTime(map.get(CLRepeatTable.repNextCreatedTime).replace("T", " "));
            if (nextDate != null) {
                Date nowDate = DateUtil.parseDateTime(DateUtil.formatDateTime(new Date()));
                if (nextDate.compareTo(nowDate) == -1) {
                    //补充子记事
                    if ("0".equals(map.get(CLRepeatTable.repInSTable)) && "0".equals(map.get(CLRepeatTable.repIsPuase))) {
                        {
                            RepeatBean bean = null;
                            if ("1".equals(map.get(CLRepeatTable.repType))) {
                                bean = RepeatDateUtil.dateTimeToChildAlarmDate(map.get(CLRepeatTable.repTime), 1, "", "", map.get(CLRepeatTable.repDisplayTime));
                            } else if ("2".equals(map.get(CLRepeatTable.repType))) {
                                bean = RepeatDateUtil.dateTimeToChildAlarmDate(map.get(CLRepeatTable.repTime), 2,
                                        map.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "").replace("\"", ""), "", map.get(CLRepeatTable.repDisplayTime));
                            } else if ("3".equals(map.get(CLRepeatTable.repType))) {
                                bean = RepeatDateUtil.dateTimeToChildAlarmDate(map.get(CLRepeatTable.repTime), 3,
                                        map.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "").replace("\"", ""), "", map.get(CLRepeatTable.repDisplayTime));
                            } else if ("4".equals(map.get(CLRepeatTable.repType))) {
                                bean = RepeatDateUtil.dateTimeToChildAlarmDate(map.get(CLRepeatTable.repTime), 4,
                                        map.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "").replace("\"", ""), "0", map.get(CLRepeatTable.repDisplayTime));
                            } else if ("6".equals(map.get(CLRepeatTable.repType))) {
                                bean = RepeatDateUtil.dateTimeToChildAlarmDate(map.get(CLRepeatTable.repTime), 4,
                                        map.get(CLRepeatTable.repTypeParameter).replace("[", "").replace("]", "").replace("\\", "").replace("\\", "").replace("\"", ""), "1", map.get(CLRepeatTable.repDisplayTime));
                            } else if ("5".equals(map.get(CLRepeatTable.repType))) {
                                bean = RepeatDateUtil.dateTimeToChildAlarmDate(map.get(CLRepeatTable.repTime), 5, "", "", map.get(CLRepeatTable.repDisplayTime));
                            }

                            if (bean != null) {
                                app.updateRepeatTimeNextDate(map.get(CLRepeatTable.repID), bean.repNextCreatedTime);
                                DownRepeatService.CreateRepeatSchNextData(map);

                                isNewChild = true;
                            }
                        }
                    }
                }
            }
        }
        if (isNewChild) {
            QueryAlarmData.writeAlarm(this);

            Intent intent = new Intent(Const.SHUAXINDATA);
            intent.putExtra("data", "success");
            intent.putExtra("index", 1);
            intent.putExtra("what", 2);
            sendBroadcast(intent);
        }

        Log.e("TAG", "CheckCreateRepeatSchData-end");
    }

    /**
     * date2比date1多的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2)   //同一年
        {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2 - day1);
        } else    //不同年
        {
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }

    class HomeKeyEventReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                final Window win = getWindow();
                win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
                win.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                loadCount();
                RepeatNotReadCount();
                UpLoadData();
                IntenetData();
                sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "0");
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        Intent intent = new Intent(context, MinAndMaxService.class);
                        intent.setAction("com.mission.schedule.service.MinAndMaxService");
                        intent.setPackage(getPackageName());
                        intent.putExtra("myfrist", "1");// 0正常进入 1最小化
                        startService(intent);
                    }
                }).start();
                sharedPrefUtil.putString(context, ShareFile.USERFILE,
                        ShareFile.OUTWEEKFAG, "0");
                sharedPrefUtil.putString(context, ShareFile.USERFILE,
                        ShareFile.OPENSTYLESTATE, "1");
                if (myIndex == 3) {
                    sharedPrefUtil.putString(context, ShareFile.USERFILE,
                            ShareFile.REFRESHFRIEND, "1");
                }

//                Intent intentioned = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
//                Bundle extras = new Bundle();
//                intentioned.putExtras(extras);
//                sendBroadcast(intentioned);
                PreUtils.RefreshAppWidget(context);
            }
        }
    }

    private void registerHomeKeyReceiver() {
        keyEventReceiver = new HomeKeyEventReceiver();
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        myIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        // 注册广播
        registerReceiver(keyEventReceiver, myIntentFilter);
    }


    /**
     * 修改极光推送的推送码
     *
     * @author lenovo
     *
     */
    /**
     * 修改推送mac地址置为空
     */
    private void ClearMAC(String macaddress) {
        if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
            if (sharedPrefUtil.getString(context,
                    ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
                final String path = URLConstants.修改MAC地址 + userId + "&uClintAddr="
                        + macaddress + "&uTocode=android";
                StringRequest request = new StringRequest(Method.GET, path,
                        new Listener<String>() {
                            @Override
                            public void onResponse(String s) {

                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                });
                request.setTag("down");
                request.setRetryPolicy(new DefaultRetryPolicy(20000, 1, 1.0f));
                App.getHttpQueues().add(request);
            }
        }
    }

    /**
     * 重要通知
     */
    private void NotificationAsync(String path) {
        StringRequest request = new StringRequest(Method.GET, path,
                new Listener<String>() {

                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    /**
     * 设置提醒模式
     */
    private void alterRingDialog() {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_setyuyin, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();

        new alterRingDialogOnClick(dialog, more_pop_menu);
    }

    class alterRingDialogOnClick implements OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView yuyin_tv;
        private TextView jingyin_tv;
        private TextView duanyin_tv;
        private TextView zd_tv;
        private TextView canel_tv;

        @SuppressLint("NewApi")
        public alterRingDialogOnClick(Dialog dialog, View view) {
            this.dialog = dialog;
            this.view = view;
            initview();
        }

        private void initview() {
            yuyin_tv = (TextView) view.findViewById(R.id.yuyin_tv);
            yuyin_tv.setOnClickListener(this);
            zd_tv = (TextView) view.findViewById(R.id.zd_tv);
            zd_tv.setOnClickListener(this);
            jingyin_tv = (TextView) view.findViewById(R.id.jingyin_tv);
            jingyin_tv.setOnClickListener(this);
            duanyin_tv = (TextView) view.findViewById(R.id.duanyin_tv);
            duanyin_tv.setOnClickListener(this);
            canel_tv = (TextView) view.findViewById(R.id.canel_tv);
            canel_tv.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.yuyin_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.RINGSTATE, "0");
                    tixingname_tv.setText("语音");
                    tixingname_tv.setTextColor(getResources().getColor(R.color.mingtian_color));
                    dialog.dismiss();
                    break;
                case R.id.jingyin_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.RINGSTATE, "1");
                    tixingname_tv.setText("静音");
                    tixingname_tv.setTextColor(getResources().getColor(R.color.sunday_txt));
                    dialog.dismiss();
                    break;
                case R.id.duanyin_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.RINGSTATE, "2");
                    tixingname_tv.setText("短音");
                    tixingname_tv.setTextColor(getResources().getColor(R.color.mingtian_color));
                    dialog.dismiss();
                    break;
                case R.id.zd_tv:
                    sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.RINGSTATE, "3");
                    tixingname_tv.setText("振动");
                    tixingname_tv.setTextColor(getResources().getColor(R.color.mingtian_color));
                    dialog.dismiss();
                    break;
                case R.id.canel_tv:
                    dialog.dismiss();
                    break;
            }
        }
    }

    // ==========================闹钟=======================================//
    private void initDate() {
//        if (!"0".equals(sharedPrefUtil.getString(context, ShareFile.USERFILE,ShareFile.FIRSTLOGIN, "0"))) {
        if (ServerUtil.isServiceRunning(context, "com.mission.schedule.service.ClockService") == false) {
            Intent intent = new Intent(this, ClockService.class);
            intent.setAction("com.mission.schedule.service.ClockService");
            intent.setPackage(getPackageName());
            intent.putExtra("WriteAlarmClockwrite", "0");
            startService(intent);
        }
    }

    /**
     * 农历
     */
//    private void downNongLiData() {
//        nongliList = app.queryMaxDate();
//        Calendar calendar = Calendar.getInstance();
//        if (nongliList != null && nongliList.size() > 0) {
//            String path = URLConstants.更新农历 + (calendar.get(Calendar.YEAR) - 1) +"-12-31";
//            StringRequest request = new StringRequest(Method.GET, path,
//                    new Listener<String>() {
//
//                        @Override
//                        public void onResponse(String s) {
//                            if (!TextUtils.isEmpty(s)) {
//                                try {
//                                    Gson gson = new Gson();
//                                    SuccessOrFailBean backBean = gson.fromJson(
//                                            s, SuccessOrFailBean.class);
//                                    if (backBean.status == 1) {
////                                        app.deletenongliData();
//                                        String nonglipath = URLConstants.下载农历;
//                                        // new
//                                        // DownNongLiAsync().execute(nonglipath);
//                                        StringRequest stringRequest = new StringRequest(Method.GET, nonglipath,
//                                                new Listener<String>() {
//
//                                                    @Override
//                                                    public void onResponse(String s) {
//                                                        if (!TextUtils.isEmpty(s)) {
//                                                            try {
//                                                                List<LunarCalendaTimeBean> list = new ArrayList<LunarCalendaTimeBean>();
//                                                                Gson gson = new Gson();
//                                                                LunarCalendaTimeBackBean backBean = gson.fromJson(s, LunarCalendaTimeBackBean.class);
//                                                                if (backBean.status == 0) {
//                                                                    list = backBean.list;
//                                                                    for (int i = 0; i < list
//                                                                            .size(); i++) {
//                                                                        app.insertNongLiData(i,
//                                                                                list.get(i).calendar,
//                                                                                list.get(i).solarTerms,
//                                                                                list.get(i).week,
//                                                                                list.get(i).lunarCalendar,
//                                                                                list.get(i).holiday,
//                                                                                list.get(i).lunarHoliday,
//                                                                                list.get(i).createTime,
//                                                                                list.get(i).isNotHoliday);
//                                                                    }
//                                                                }
//                                                            } catch (JsonSyntaxException e) {
//                                                                e.printStackTrace();
//                                                            }
//                                                        }
//                                                    }
//                                                },
//                                                new Response.ErrorListener() {
//
//                                                    @Override
//                                                    public void onErrorResponse(
//                                                            VolleyError volleyError) {
//
//                                                    }
//                                                });
//                                        stringRequest.setTag("down");
//                                        stringRequest
//                                                .setRetryPolicy(new DefaultRetryPolicy(
//                                                        20000, 1, 1.0f));
//                                        App.getHttpQueues().add(stringRequest);
//                                    }
//                                } catch (JsonSyntaxException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        }
//                    }, new Response.ErrorListener() {
//
//                @Override
//                public void onErrorResponse(VolleyError error) {
//
//                }
//            });
//            request.setTag("down");
//            request.setRetryPolicy(new DefaultRetryPolicy(20000, 1, 1.0f));
//            App.getHttpQueues().add(request);
//        } else {
//            String nonglipath = URLConstants.下载农历;
//            StringRequest stringRequest = new StringRequest(Method.GET,
//                    nonglipath, new Listener<String>() {
//
//                @Override
//                public void onResponse(String s) {
//                    if (!TextUtils.isEmpty(s)) {
//                        try {
//                            List<LunarCalendaTimeBean> list = new ArrayList<LunarCalendaTimeBean>();
//                            Gson gson = new Gson();
//                            LunarCalendaTimeBackBean backBean = gson
//                                    .fromJson(
//                                            s,
//                                            LunarCalendaTimeBackBean.class);
//                            if (backBean.status == 0) {
//                                list = backBean.list;
//                                for (int i = 0; i < list.size(); i++) {
//                                    app.insertNongLiData(i,
//                                            list.get(i).calendar,
//                                            list.get(i).solarTerms,
//                                            list.get(i).week,
//                                            list.get(i).lunarCalendar,
//                                            list.get(i).holiday,
//                                            list.get(i).lunarHoliday,
//                                            list.get(i).createTime,
//                                            list.get(i).isNotHoliday);
//                                }
//                            }
//                        } catch (JsonSyntaxException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }, new Response.ErrorListener() {
//
//                @Override
//                public void onErrorResponse(VolleyError volleyError) {
//
//                }
//            });
//            stringRequest.setTag("down");
//            stringRequest
//                    .setRetryPolicy(new DefaultRetryPolicy(20000, 1, 1.0f));
//            App.getHttpQueues().add(stringRequest);
//            // new DownNongLiAsync().execute(nonglipath);
//        }
//    }

    /**
     * 实现文本复制功能
     *
     * @param content
     * @author lenovo
     */
    public static void copy(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (!"".equals(StringUtils.getIsStringEqulesNull(content))) {
            cmb.setText(content.trim());
        }
    }

    /**
     * 实现粘贴功能
     *
     * @param context
     * @return
     * @author lenovo
     */
    public static String paste(Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        return cmb.getText().toString().trim();
    }

    public void onEventMainThread(PostSendMainActivity event) {
        int index = event.getIndex();
        if (index == 1) {
            int noEndCount = event.getMsg();
            if (noEndCount == 0) {
                tv_schedule_count.setVisibility(View.GONE);
            } else {
                tv_schedule_count.setText(noEndCount + "");
                tv_schedule_count.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 查询发送日程主菜单new信息
     */
    private void getFriendLyNumS() {
        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST + "/appFrends_findFrendsPostNum.do",
                new Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Intent intent1 = new Intent();
                        intent1.setAction("ntype");
                        intent1.putExtra("l", 1);
                        sendBroadcast(intent1);
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getInt("status") == 0) {
//                                    tv_my_new.setVisibility(View.VISIBLE);
                                    Intent intent = new Intent();
                                    intent.setAction("ly");
                                    intent.putExtra("l", 1);
                                    sendBroadcast(intent);
                                } else {
//                                    tv_my_new.setVisibility(View.GONE);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userId);
                return map;
            }
        };
        stringRequest.setTag("findLyNewNum");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    /**
     * 图片加载第一次显示监听器
     *
     * @author Administrator
     */
    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                // 是否第一次显示
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    /**
     * 下载新信息
     */
    public void DownNewInforMation() {
        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST + "/appFrends_downUserNewLy.do",
                new Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();

                                UserNewLy userNewLy = gson.fromJson(result, UserNewLy.class);
                                Log.e("TAG", result);
                                if (userNewLy.status == 0) {

                                    sharedPrefUtil.putString(MainActivity.this,
                                                    ShareFile.USERFILE,ShareFile.UPDATESETTIME,
                                                    userNewLy.downTime.replace('T', ' '));

                                    List<UserNewLy.ListBean> listBeanList = userNewLy.list;
                                    List<UserNewLy.DeListBean> deListBeanList = userNewLy.delList;

                                    if (listBeanList != null) {
                                        for (UserNewLy.ListBean bean : listBeanList) {
                                            App.getDBcApplication().insertNewInformationLy(bean);
                                        }
                                        if (deListBeanList != null) {
                                            for (UserNewLy.DeListBean bean : deListBeanList) {
                                                App.getDBcApplication().deleteNewInformationLy(bean.id);
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();

                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "MainActivity---downUserNewLy---error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userId);// "52432"
                return map;
            }
        };
        stringRequest.setTag("downUserNewLy");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    class newnums extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Integer.valueOf(intent.getExtras().get("l").toString()) == 1) {
                Message message = new Message();
                message.what = 101;
                handler.sendMessage(message);
            } else if (Integer.valueOf(intent.getExtras().get("l").toString()) == 2) {
                Message message = new Message();
                message.what = 102;
                handler.sendMessage(message);
            }
        }
    }

    class LoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkBoxState(0);
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return "V" + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "V6.3.2";
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public int getVersionCode(int code) {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return code;
        }
    }

    private void updateLoginDate() {
        if (sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            if (!userId.substring(0, 1).equals("-")) {
                String path = URLConstants.更新用户最后登录时间 + userId
                        + "&userOpenId=1&version=" + getVersion() + "&phoneType="
                        + android.os.Build.MANUFACTURER + "-"
                        + android.os.Build.MODEL.replace(" ", "");// android.os.Build.MODEL
                StringRequest request = new StringRequest(Method.GET, path,
                        new Listener<String>() {

                            @Override
                            public void onResponse(String s) {
                                if (!TextUtils.isEmpty(s)) {
                                    try {
                                        Gson gson = new Gson();
                                        SuccessOrFailBean bean = gson.fromJson(s,
                                                SuccessOrFailBean.class);
                                        if (bean.status == 0) {
                                            sharedPrefUtil.putString(getApplication(),
                                                    ShareFile.USERFILE,
                                                    ShareFile.ENDLOGINDATE,
                                                    DateUtil.formatDate(new Date()));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {

                    }
                });
                request.setTag("down");
                request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                App.getHttpQueues().add(request);
            }
        } else {
            int sid = Math.abs(Integer.valueOf(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0")));
            String path = URLConstants.新游客试用 + "?phoneType=" + android.os.Build.MODEL.replace(" ", "") + "&id=" + sid + "&version=" + getVersion() + "&pushMac=" + JPushInterface.getRegistrationID(context);
            StringRequest request = new StringRequest(Method.GET, path,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String result) {
                            String re = result;
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
            request.setTag("resgin");
            request.setRetryPolicy(new DefaultRetryPolicy(3000, 1, 1.0f));
            App.getHttpQueues().add(request);
        }
    }

    private void getAPPVersion() {
        HttpUtils httpUtils = new HttpUtils(5000);
        httpUtils.send(HttpMethod.POST, URLConstants.获取最新版本号, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Gson gson = new Gson();
                    AppVersionBean appversionbean = gson.fromJson(responseInfo.result, AppVersionBean.class);
                    if (appversionbean.status == 0) {
                        List<AppVersionBean.ListBean> list = appversionbean.list;
                        if (list != null) {
                            for (AppVersionBean.ListBean bean : list) {
                                if (Integer.valueOf(bean.android) > getVersionCode(Integer.valueOf(bean.android))) {
                                    updateApp(bean.android);
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    private void updateApp(final String version) {
        final AlertDialog builder = new AlertDialog.Builder(this).create();
        builder.setCancelable(false);
        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alter);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        TextView delete_tv = (TextView) window.findViewById(R.id.delete_tv);
        TextView cancle_tv = (TextView) window.findViewById(R.id.cancle_tv);
        cancle_tv.setText("暂不更新");
        cancle_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        delete_tv.setText("已有新版本，请下载更新！");
        delete_ok.setText("立即更新");
        delete_ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
                Intent intent = new Intent(context, DownAPKService.class);
                intent.setAction("DownAPK");
                startService(intent);
            }
        });
    }

    private void getUser_findTbUserMac() {
        updateLoginDate();
        HttpUtils httpUtils = new HttpUtils(5000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("uId", userId);
        httpUtils.send(HttpMethod.POST, URLConstants.获取MAC地址, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException e, String msg) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        if (!TextUtils.isEmpty(responseInfo.result)) {
                            Gson gson = new Gson();
                            MacAddressBean macAddressBean = gson.fromJson(responseInfo.result, MacAddressBean.class);
                            if (macAddressBean.status == 0) {
                                List<MacAddressBean.ListBean> list = macAddressBean.list;
                                if (list != null && list.size() > 0) {
                                    if (!list.get(0).mac.equals(JPushInterface.getRegistrationID(context))) {
                                        String login_user = sharedPrefUtil.getString(
                                                getApplication(), ShareFile.USERFILE, ShareFile.TELEPHONE, "");
                                        if (login_user.isEmpty()) {
                                            login_user = sharedPrefUtil.getString(
                                                    getApplication(), ShareFile.USERFILE, ShareFile.USEREMAIL, "");
                                        }
                                        WriteAlarmClock.clearAlarmClock(getApplicationContext());
                                        if (!"".equals(sharedPrefUtil.getString(context,
                                                ShareFile.USERFILE, ShareFile.TELEPHONE, ""))) {
                                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                    ShareFile.TELEPHONE, "");
                                        } else {
                                            sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                    ShareFile.USEREMAIL, "");
                                        }
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.QIANDAOSTRING, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.ISADMIN, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.USERID, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.USERNAME, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.USERBACKGROUNDPATH, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.USERPHOTOPATH, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.USERSTATE, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.FIRSTLOGIN, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.U_ACC_NO, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.MAXFOCUSID, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.OUTWEEKFAG, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.UPDATESETTIME, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.UPDATENOTESETTIME, "2016-01-01");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.DOWNSCHTIME, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.DOWNREPTIME, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.RINGSTATE, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.ISYOUKE, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.DOWNTAGDATE, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.OPENSTYLESTATE, "2");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.FRIENDDOWNSCHTIME, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.FRIENDDOWNRepTIME, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.FRIENDDOWNOldTIME, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.PUSH_ALIAS, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.REFRESHFRIEND, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.FIRSTDOWNFOCUSSCH, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.SHOUCANGDATA, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.DOWNNEWFOCUSSHARESCHDATE, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.DOWNNEWFOCUSSHAREREPDATE, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.KuaiJieSouSuo, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.SHAREDATA, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.LOCALPATH, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.ISMOSTIMAGE, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.ISSJMOSTIMAGE, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.CUSTIOMMOSTIMAGE1, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.CUSTIOMMOSTIMAGE2, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.CUSTIOMMOSTIMAGE3, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.CUSTIOMMOSTIMAGE4, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.CUSTIOMMOSTIMAGE5, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.CUSTIOMMOSTIMAGE6, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.CUSTIOMMOSTIMAGE7, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.DQRBEFORETIME, "4320");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.ZJF, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.UNTASKEND, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.PERSONDOWNTIME, "2016-01-01");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.ISNEWYOUKE, "0");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ZDTX, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.BDTX, "");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISTX, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.WELCOMETOLOGIN, "1");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.WEEKCOLOR1, "4");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.MONTHCOLOR2, "3");
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE,
                                                ShareFile.YEARCOLOR3, "2");
                                        ClearMAC("");
                                        app.douleClear();
                                        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONDOWNTIME, "2016-01-01");
                                        Intent newlogin = new Intent(context, PhoneCodeLoginNewActivity.class);
                                        newlogin.putExtra("user", login_user);
                                        startActivity(newlogin);
//                                        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
//                                        Bundle extras = new Bundle();
//                                        intentappwidget.putExtras(extras);
//                                        sendBroadcast(intentappwidget);
                                        activityManager.doAllActivityFinish();
                                    }
                                }
                            }
                        }
                    }
                });
    }


    class MacAddressBean {

        /**
         * message : 成功
         * status : 0
         * list : [{"createTime":"2017-04-28T10:31:00",
         * "changeTime":"1970-01-01T08:00:00",
         * "mac":"09fb47ca 04f1bf3a 71f07485 b0d509c1 0440ce6e 9b4f28ec 425b7aa2 039de2ef",
         * "uid":1140656,"remark":null}]
         */

        public String message;
        public int status;
        public List<ListBean> list;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public class ListBean {
            /**
             * createTime : 2017-04-28T10:31:00
             * changeTime : 1970-01-01T08:00:00
             * mac : 09fb47ca 04f1bf3a 71f07485 b0d509c1 0440ce6e 9b4f28ec 425b7aa2 039de2ef
             * uid : 1140656
             * remark : null
             */

            public String createTime;
            public String changeTime;
            public String mac;
            public int uid;
            public Object remark;

            public String getCreateTime() {
                return createTime;
            }

            public void setCreateTime(String createTime) {
                this.createTime = createTime;
            }

            public String getChangeTime() {
                return changeTime;
            }

            public void setChangeTime(String changeTime) {
                this.changeTime = changeTime;
            }

            public String getMac() {
                return mac;
            }

            public void setMac(String mac) {
                this.mac = mac;
            }

            public int getUid() {
                return uid;
            }

            public void setUid(int uid) {
                this.uid = uid;
            }

            public Object getRemark() {
                return remark;
            }

            public void setRemark(Object remark) {
                this.remark = remark;
            }
        }
    }

    class Beans {

        /**
         * list : [{"createTime":"2017-02-15T10:36:33","id":2,"integrals":0,"phoneType":"ios","remark":null,"remark1":null,"versions":0}]
         * message : 游客登陆成功
         * status : 0
         */

        public String message;
        public int status;
        public List<ListBean> list;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public class ListBean {
            /**
             * createTime : 2017-02-15T10:36:33
             * id : 2
             * integrals : 0
             * phoneType : ios
             * remark : null
             * remark1 : null
             * versions : 0
             */

            public String createTime;
            public int id;
            public int integrals;
            public String phoneType;
            public Object remark;
            public Object remark1;
            public int versions;

            public String getCreateTime() {
                return createTime;
            }

            public void setCreateTime(String createTime) {
                this.createTime = createTime;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public int getIntegrals() {
                return integrals;
            }

            public void setIntegrals(int integrals) {
                this.integrals = integrals;
            }

            public String getPhoneType() {
                return phoneType;
            }

            public void setPhoneType(String phoneType) {
                this.phoneType = phoneType;
            }

            public Object getRemark() {
                return remark;
            }

            public void setRemark(Object remark) {
                this.remark = remark;
            }

            public Object getRemark1() {
                return remark1;
            }

            public void setRemark1(Object remark1) {
                this.remark1 = remark1;
            }

            public int getVersions() {
                return versions;
            }

            public void setVersions(int versions) {
                this.versions = versions;
            }
        }
    }

    public class AppVersionBean {

        /**
         * list : [{"android":"609","ios":"735"}]
         * message : 成功
         * status : 0
         */

        public String message;
        public int status;
        public List<ListBean> list;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public class ListBean {
            /**
             * android : 609
             * ios : 735
             */

            public String android;
            public String ios;

            public String getAndroid() {
                return android;
            }

            public void setAndroid(String android) {
                this.android = android;
            }

            public String getIos() {
                return ios;
            }

            public void setIos(String ios) {
                this.ios = ios;
            }
        }
    }
}


/**
 * 04-20 14:46:24.311 31493-31493/? E/ANR_LOG: >>> msg's executing time is too long
 * Blocked msg = { when=-30s555ms what=0 target=android.os.Handler callback=com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable } , cost  = 30555 ms
 * 04-20 14:46:24.312 31493-31493/? E/ANR_LOG: >>>Current msg List is:
 * Current msg <1>  = { when=-29s976ms what=2 target=com.lidroid.xutils.task.PriorityAsyncTask$InternalHandler obj=com.lidroid.xutils.task.PriorityAsyncTask$AsyncTaskResult@10dacce }
 * Current msg <2>  = { when=-29s975ms what=1 target=com.lidroid.xutils.task.PriorityAsyncTask$InternalHandler obj=com.lidroid.xutils.task.PriorityAsyncTask$AsyncTaskResult@2cd87ef }
 * >>>CURRENT MSG DUMP OVER<<<
 * <p>
 * <p>
 * 04-20 14:48:47.906 32011-32011/? E/ANR_LOG: >>> msg's executing time is too long
 * Blocked msg = { when=-30s579ms what=0 target=android.os.Handler callback=com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable } , cost  = 30578 ms
 * >>>Current msg List is:
 * Current msg <1>  = { when=-30s200ms what=2 target=com.lidroid.xutils.task.PriorityAsyncTask$InternalHandler obj=com.lidroid.xutils.task.PriorityAsyncTask$AsyncTaskResult@36cf6c9 }
 * Current msg <2>  = { when=-30s200ms what=1 target=com.lidroid.xutils.task.PriorityAsyncTask$InternalHandler obj=com.lidroid.xutils.task.PriorityAsyncTask$AsyncTaskResult@10c81ce }
 * Current msg <3>  = { when=-23s118ms what=132 target=android.app.ActivityThread$H }
 * >>>CURRENT MSG DUMP OVER<<<
 * <p>
 * 04-20 14:52:23.224 32011-32022/? I/art: Background sticky concurrent mark sweep GC freed 306295(12MB) AllocSpace objects, 74(6MB) LOS objects, 35% free, 35MB/55MB, paused 1.301ms total 101.997ms
 * 04-20 14:52:26.449 1556-3394/? D/GNPProxy: onLocationChanged: fused
 * <p>
 * <p>
 * 04-20 14:53:07.454 1556-1570/? D/ActivityManager: pkgName: com.mission.schedule userId: 0 killed for back_key
 * 04-20 14:53:07.455 1556-1570/? I/ActivityManager: Force stopping com.mission.schedule appid=10162 user=0: from pid 1556
 * 04-20 14:53:07.457 1556-1570/? I/ActivityManager: Killing 32011:com.mission.schedule/u0a162 (adj 200): stop com.mission.schedule
 * 04-20 14:53:07.467 1556-1570/? D/ActivityManager: cleanUpApplicationRecord -- 32011
 * 04-20 14:53:07.473 1556-1570/? I/ActivityManager:   Force stopping service ServiceRecord{f22db22 u0 com.mission.schedule/.service.NoteService}
 * Force stopping service ServiceRecord{387e561 u0 com.mission.schedule/.service.UpdataTagService}
 * Force stopping service ServiceRecord{28f601f u0 com.mission.schedule/.service.LoginDownDataService}
 * Force stopping service ServiceRecord{f618420 u0 com.mission.schedule/.service.LocalSynService}
 * Force stopping service ServiceRecord{4ebc80d u0 com.mission.schedule/.service.NoteDService}
 * Force stopping service ServiceRecord{400c2f9 u0 com.mission.schedule/.service.ClockService}
 * Force stopping service ServiceRecord{fdf6306 u0 com.mission.schedule/cn.jpush.android.service.PushService}
 * Force stopping service ServiceRecord{f845625 u0 com.mission.schedule/.service.MTimeService}
 * Force stopping service ServiceRecord{2ce3fa4 u0 com.mission.schedule/.service.DownQianDaoService}
 * Force stopping service ServiceRecord{c1b5c69 u0 com.mission.schedule/.service.DownImageService}
 * <p>
 * <p>
 * 04-20 14:56:21.376 2506-2506/? E/ANR_LOG: >>> msg's executing time is too long
 * Blocked msg = { when=-30s344ms what=0 target=android.os.Handler callback=com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable } , cost  = 30344 ms
 * >>>Current msg List is:
 * Current msg <1>  = { when=-24s39ms what=132 target=android.app.ActivityThread$H }
 * >>>CURRENT MSG DUMP OVER<<<
 */
